﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FilesExplorer.Components
{
    internal class FileTreeView
    {
        TreeView treeView1;
        ListView listView1;

        public FileTreeView(TreeView treeView, FileListView filelistView)
        {
            treeView1 = treeView;
            treeView1.BeforeExpand += TreeView1_BeforeExpand;
            treeView1.BeforeCollapse += TreeView1_BeforeCollapse;
            treeView1.AfterSelect += TreeView1_AfterSelect;
            InitializeTreeView();

            filelistView.FolderRenamed += OnFolderRenamed;
            filelistView.Refreshed += OnRefreshed;
            filelistView.FolderSearched += OnFolderSearched;
        }

        private void InitializeTreeView()
        {
            // 初始化C盘根目录
            TreeNode rootNode = new TreeNode("C:\\");
            treeView1.Nodes.Add(rootNode);

            // 为根节点加载顶层目录，显示为TreeNode
            LoadTopLevelDirectories(rootNode);
        }

        private void LoadTopLevelDirectories(TreeNode node)
        {
            string rootPath = node.Text; // 根路径 C:\
            try
            {
                string[] directories = Directory.GetDirectories(rootPath); // 获取顶层文件夹

                foreach (string directory in directories)
                {
                    TreeNode dirNode = new TreeNode(Path.GetFileName(directory)); // 创建子节点
                    dirNode.Nodes.Add(new TreeNode("Loading...")); // 为子节点添加虚拟节点

                    node.Nodes.Add(dirNode); // 添加到父节点
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 如果没有访问权限，在这里处理异常
                MessageBox.Show("访问权限异常");
            }
            catch (Exception)
            {
                // 其他异常处理
                MessageBox.Show("加载顶层文件夹异常");
            }
        }

        private void TreeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode selectedNode = e.Node;

            // 如果当前节点下有一个虚拟的 "Loading..." 子节点，说明需要加载子文件夹
            if (selectedNode.Nodes[0].Text == "Loading...")
            {
                selectedNode.Nodes.Clear(); // 清除虚拟节点
                LoadSubDirectories(selectedNode); // 加载子文件夹
            }
        }

        private void LoadSubDirectories(TreeNode node)
        {
            string path = GetFullPathFromNode(node); // 获取节点对应的路径
            try
            {
                string[] subDirectories = Directory.GetDirectories(path); // 获取子文件夹

                foreach (string subDirectory in subDirectories)
                {
                    TreeNode subNode = new TreeNode(Path.GetFileName(subDirectory));

                    // 如果子文件夹还有子目录，则添加虚拟节点
                    if (Directory.GetDirectories(subDirectory).Length > 0)
                    {
                        subNode.Nodes.Add(new TreeNode("Loading..."));
                    }

                    node.Nodes.Add(subNode); // 添加子节点到当前节点
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 处理没有权限访问的文件夹
                MessageBox.Show("访问权限异常");
            }
        }

        private void TreeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e){ }

        public event Action<string> FolderSelected;

        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;
            string path = GetFullPathFromNode(node);
            FolderSelected?.Invoke(path); // 触发事件，通知ListView更新
        }

        private void OnFolderRenamed(string oldPath, string newPath)
        {
            TreeNode node = FindNodeByPath(treeView1.Nodes, oldPath);
            if (node != null)
            {
                node.Text = Path.GetFileName(newPath);
                node.Tag = newPath;
            }
        }

        private void OnRefreshed()
        {
            treeView1.Nodes.Clear();
            InitializeTreeView();
        }

        private void OnFolderSearched(string path)
        {
            TreeNode node = FindNodeByPath(treeView1.Nodes, path);
            if (node != null)
            {
                treeView1.SelectedNode = node;
            }
        }

        private string GetFullPathFromNode(TreeNode node)
        {
            string path = node.Text;
            while (node.Parent != null)
            {
                node = node.Parent;
                path = Path.Combine(node.Text, path); // 拼接路径
            }
            return path;
        }

        private TreeNode FindNodeByPath(TreeNodeCollection nodes, string path)
        {
            foreach (TreeNode node in nodes)
            {
                if (GetFullPathFromNode(node) == path)
                {
                    return node;
                }
                TreeNode foundNode = FindNodeByPath(node.Nodes, path);
                if (foundNode != null)
                {
                    return foundNode;
                }
            }
            return null;
        }

    }
}
